//
//  SearchVC.swift
//  DLuxTravel
//
//  Created by 陆涛 on 2018/11/22.
//  Copyright © 2018 imguider. All rights reserved.
//

import UIKit
import Fuse

class SearchVC: BaseVC {
    
    let searchBar:UISearchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: CGFloat(kScreenWidth) * 2 / 3 , height: 40))
    
    @IBOutlet weak var tableView: UITableView!
    
    
    var books = [String]()
    var filteredBooks = [NSAttributedString]()
    
    var isSearching:Bool {
        
        if searchBar.text != "" {
            return true
        }
        
        return false
    }
    
    let fuse = Fuse()

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        setupData()
    }

    private func setupUI() {
        
        setNavBarStyle(.black)
        
        searchBar.delegate = self
        
        self.navigationItem.titleView = searchBar
        
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        
        self.addRightItem(title:"取消") {
            
            [weak self] in
            guard let `self` = self else { return }
            
            self.dismiss(animated: true, completion: nil)
        }
    }
    
    private func setupData() {
        
        books = [
            "Angels & Demons",
            "Old Man's War",
            "The Lock Artist",
            "HTML5",
            "Right Ho Jeeves",
            "The Code of the Wooster",
            "Thank You Jeeves",
            "The DaVinci Code",
            "The Silmarillion",
            "Syrup",
            "The Lost Symbol",
            "The Book of Lies",
            "Lamb",
            "Fool",
            "Incompetence",
            "Fat",
            "Colony",
            "Backwards, Red Dwarf",
            "The Grand Design",
            "The Book of Samson",
            "The Preservationist",
            "Fallen",
            "Monster 1959"
        ]
    }
    
    private func filterContentForSearchText(_ searchText: String) {
        
        let boldAttrs = [
            NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 17),
            NSAttributedString.Key.foregroundColor: UIColor.blue
        ]
        
        let results = fuse.search(searchText, in: books)
        
        filteredBooks = results.map { (index, _, matchedRanges) in
            let book = books[index]
            
            let attributedString = NSMutableAttributedString(string: book)
            matchedRanges
                .map(Range.init)
                .map(NSRange.init)
                .forEach {
                    attributedString.addAttributes(boldAttrs, range: $0)
            }
            
            return attributedString
        }
        
        tableView.reloadData()
    }
}

extension SearchVC: UISearchBarDelegate {
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        
        filterContentForSearchText(searchBar.text!)
    }
}

extension SearchVC: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if isSearching {
            return filteredBooks.count
        }
        
        return books.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
        let item: NSAttributedString
        
        if isSearching {
            item = filteredBooks[indexPath.row]
        } else {
            item = NSAttributedString(string: books[indexPath.row])
        }
        
        cell.textLabel!.attributedText = item
        
        return cell
    }
}
